package com.zimmur.controller;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zimmur.common.ConstData;
import com.zimmur.model.account.User;
import com.zimmur.service.IUserService;
import com.zimmur.tools.CheckMobile;


public class BaseController{
	private static Logger log=LoggerFactory.getLogger(BaseController.class);
	@Resource
	private IUserService userService;
	
	/**
     * 请求上下文
     */
    private static ThreadLocal<HttpServletRequest>  request_thread_local = new ThreadLocal<HttpServletRequest>() ;
    /**
     * 应答上下文
     */
    private static ThreadLocal<HttpServletResponse>  response_thread_local = new ThreadLocal<HttpServletResponse>() ;;
    	
	/*
	@ExceptionHandler
    public String exception(HttpServletRequest request, Exception e) {
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status=StatusCodeEnum.CODE100000;
		entity.setCode(status.getCode());
		entity.setMsg(e.getMessage());
		return JSON.toJSONString(entity);
		
	}*/
	
	
	public static void setRequest(HttpServletRequest request) {
		 request_thread_local.set(request);
	}


	public static void setResponse(HttpServletResponse response) {
		response_thread_local.set(response);
	}


	/**
     * 当前的请求对象
     * @return
     */
    protected HttpServletRequest getRequest(){
        return request_thread_local.get();
    }
    
    /**
     * 获取当前的应答对象
     * @return
     */
    protected HttpServletResponse getResponse(){
        return response_thread_local.get();
    }
    
    /**
     * 移除当前Request
     */
    public static void removeRequest(){
    	request_thread_local.remove();
    }
    /**
     * 移除当前Reponse
     */
    public static void removeResponse(){
    	response_thread_local.remove();
    }
   /**
    * 获取远程访问IP
    * @return
    */
   
   protected String getRemoteIp(){
	   String remoteIp = null;
       HttpServletRequest request = this.getRequest();
      remoteIp = request.getHeader("x-forwarded-for");
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getHeader("X-Real-IP");
       }
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getHeader("Proxy-Client-IP");
       }
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getHeader("WL-Proxy-Client-IP");
       }
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getHeader("HTTP_CLIENT_IP");
       }
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getHeader("HTTP_X_FORWARDED_FOR");
       }
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getRemoteAddr();
       }
       if (remoteIp == null ||remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
          remoteIp= request.getRemoteHost();
       }
       return remoteIp.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":remoteIp;
   }
   /*********************获取访问参数*******************/
   /**
    * 获取所有参数
    * @return
    */
   protected Map<String,String[]> getParams(){
       HttpServletRequest request = this.getRequest();
       return request.getParameterMap();
   }
   /**
    * 获取指定的配置
    * @param name
    * @return
    */
   protected String getParam(String name){
       return getParam(name, "");
   }
   /**
    * 根据参数名称获取参数值，如果没有找到则以默认值返回
    * @param name
    * @param defaultValue
    * @return
    */
   protected String getParam(String name, String defaultValue){
       HttpServletRequest request = this.getRequest();
       String strValue = request.getParameter(name);
       return strValue == null ? defaultValue : strValue;
   }
   /**
    * 获取整形的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected int getIntParam(String name){
       return getParam(name, 0);
   }
   /**
    * 获取整形的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected int getParam(String name, Integer defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Integer.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   /**
    * 获取长整形的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected long getLongParam(String name){
       return getParam(name, 0L);
   }
   /**
    * 获取长整形的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected long getParam(String name, Long defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Long.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   /**
    * 获取单精度的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected float getFloatParam(String name){
       return getParam(name, 0F);
   }
   /**
    * 获取单精度的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected float getParam(String name, Float defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Float.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   /**
    * 获取双精度的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected double getDoubleParam(String name){
       return getParam(name, 0D);
   }
   /**
    * 获取双精度的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected double getParam(String name, Double defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Double.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   /**
    * 获取字节的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected byte getByteParam(String name){
       return getParam(name, (byte)0);
   }
   /**
    * 获取字节的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected byte getParam(String name, Byte defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Byte.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   /**
    * 获取字节的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected short getShortParam(String name){
       return getParam(name, (short)0);
   }
   /**
    * 获取字节的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected short getParam(String name, Short defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Short.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   /**
    * 获取布尔的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected boolean getBooleanParam(String name){
       return getParam(name, false);
   }
   /**
    * 获取布尔的参数值
    * @param name
    * @param defaultValue
    * @return
    */
   protected boolean getParam(String name, Boolean defaultValue){
       String strValue = getParam(name, defaultValue.toString());
       try{
           return Boolean.valueOf(strValue);
       }
       catch(Exception e){
           return defaultValue;
       }
   }
   
   
   /*********************获取访问参数*******************/
   /**
    * 获取Token用户ID
    * @return
    */
   protected long getTokenUserId(){
	   long userId = 0;
	   String token = getParam(ConstData.USER_ACCESS_TOKEN);
       if (token != null) {
    	   userId = userService.getUserIdByToken(token);
       }
	   return userId;
   }
   /**
    * 获取token
    * @return
    */
   protected String getToken() {
	   return getParam(ConstData.USER_ACCESS_TOKEN);
   }
   protected String getDomainUrl(){
	   return getRequest().getScheme()+"://"+ getRequest().getServerName();
   }
   
   protected String getCurrentUrl(){
	   return getDomainUrl()+getRequest().getRequestURI();
   }
   /** 
    * 检查访问方式是否为移动端 
    *  
    * @Title: checkMobile 
    * @Date : 2016-8-15 下午19:40:00 
    * @param request 
    * @throws IOException  
    */  
   public boolean checkIsMobile()throws IOException{
	   boolean isFromMobile=false; 
	   
	   try{  
           //获取ua，用来判断是否为移动端访问  
           String userAgent = this.getRequest().getHeader("USER-AGENT" ).toLowerCase();    
           if(null == userAgent){    
               userAgent = "";    
           }  
           isFromMobile=CheckMobile.check(userAgent);  
           //判断是否为移动端访问  
           if(isFromMobile){  
        	   log.info("移动端访问");
           } else {  
        	   log.info("pc端访问");
           }  
       }catch(Exception e){
    	   log.error(e.getMessage());
       }  
	   return isFromMobile;  
   }
   
   /**
    * 验证用户是否有效
    */
   public boolean checkUserValidate(){
	   boolean bRet = false;
		try {
			User user = userService.getUserInfoByUserId(getTokenUserId());
			if(user != null && user.getIsValide() == 1){
				bRet = true;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	   return bRet;
   }
   /**
    * 游客身份验证
    * @param guessUserId
    * @return
    */
   public boolean isGuess(String guessUserId){
	   boolean flag=false;
	   try {
		   long userId=getTokenUserId();
		   long guessId=Long.valueOf(guessUserId);
		   flag= userId==guessId;
	} catch (NumberFormatException e) {
		log.error(e.getMessage(),e);
	}
	   return flag;
   }
  
}
